//
//  CYCopyViewController.m
//  CreditAddressBook
//
//  Created by Mosu&Cuu on 15/9/14.
//  Copyright (c) 2015年 Lee. All rights reserved.
//

#import "CYCopyViewController.h"
#import "CYMeTVC.h"
#import "CYMeHttpTool.h"
#import "CYTool.h"
#import "CYUser.h"
#import "CYLoginHttpTool.h"
#import "CYJsonInfo.h"
#import "NSObject+MJKeyValue.h"
#import "CYHttpTool.h"
#import "CYABDetailVController.h"
#import "AddressBook.h"
#import "CYAddressBookCell.h"
#import "CYABTool.h"
#import "CYCloudPerson.h"
#import "CYMeTool.h"
#import "MBProgressHUD+MJ.h"
#import <QuartzCore/QuartzCore.h>
#import "AFURLRequestSerialization.h"
#import "AFNetworking.h"
#import "AFHTTPRequestOperation.h"
#import "RegexKitLite.h"
#import "LERange.h"
#import "CYDatabase.h"

@interface CYCopyViewController ()
{
    CAShapeLayer *arcLayer;
    BOOL _isIntroduceVC;
    NSInteger numberOfHeigt;
}

@property (nonatomic,strong) NSDictionary *netpeople;
@property (nonatomic,strong) UILabel *netpllb;
@property (nonatomic,strong) UILabel *tmlb;
@property (nonatomic,strong) UILabel *cplb;
@property (nonatomic,strong) NSString *versioncp;
@property (nonatomic,strong) NSString *versiongt;
@property (nonatomic,strong) UIButton *cpBtn;
@property (nonatomic,strong) UIButton *gtBtn;
@property (nonatomic,strong) UIButton *cpbtnlb;
@property (nonatomic,strong) UILabel *copylb;

@end

@implementation CYCopyViewController


- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupNavigationView];
    self.view.backgroundColor = [UIColor whiteColor];
    self.title = @"云同步";
    // Do any additional setup after loading the view.
    [self createUI];
}

-(void)viewWillAppear:(BOOL)animated {
    
    _cpBtn.hidden = YES;
    _cpbtnlb.hidden = NO;
    _cpbtnlb = [[UIButton alloc]initWithFrame:CGRectMake(self.view.width/5, self.view.height/1.2,self.view.width/4,30)];
    _cpbtnlb.layer.borderWidth = 0.8;
    _cpbtnlb.layer.cornerRadius = 8.0;
    _cpbtnlb.layer.borderColor = [UIColor clearColor].CGColor;
    _cpbtnlb.backgroundColor = CYColor(131, 195, 111, 1);
    [_cpbtnlb setTitle:@"云备份" forState:UIControlStateNormal];
    [self.view addSubview: _cpbtnlb];
    CYUser *user = [CYLoginHttpTool  userData].user;
    [CYHttpTool postWithURL:[CYURL getNewVersionTime] params:@{@"userId":user.userId} success:^(id json) {
        CYJsonInfo *jsonInfo = [CYJsonInfo objectWithKeyValues:json]; NSDictionary *messageDic = jsonInfo.message;
        _versiongt = messageDic[@"time"];
//        CYLog(@"versongt = %@",_versiongt);
        _tmlb = [[UILabel alloc]initWithFrame:CGRectMake(self.view.width/10,_netpllb.y+_netpllb.height, 300, 30)];
        _tmlb.textColor = CYColor(131, 195, 111, 1);
        _tmlb.font = [UIFont fontWithName:@"" size:5.0];
        _tmlb.text = [NSString stringWithFormat:@"最新备份节点:%@",_versiongt];
        _tmlb.font = [UIFont systemFontOfSize:16.0];
        _cpBtn.hidden = NO;
        _cpbtnlb.hidden=YES;
        [self.view addSubview:_tmlb];
    } failure:^(NSError *error) {
        
    }];

}

- (void)createUI {
    
    _cpBtn = [[UIButton alloc]initWithFrame:CGRectMake(self.view.width/5, self.view.height/1.2,self.view.width/4,30)];
    _cpBtn.showsTouchWhenHighlighted = YES;
    [_cpBtn setTitle:@"云备份" forState:UIControlStateNormal];
    _cpBtn.layer.borderWidth = 0.8f;
    _cpBtn.layer.cornerRadius = 8.0f;
    _cpBtn.layer.borderColor = [UIColor clearColor].CGColor;
    _cpBtn.backgroundColor = CYColor(131, 195, 111, 1);
    [_cpBtn addTarget:self action:@selector(copycloud:) forControlEvents:UIControlEventTouchUpInside];
    
    _gtBtn = [[UIButton alloc] initWithFrame:CGRectMake(self.view.width/1.8, _cpBtn.y, _cpBtn.width, _cpBtn.height)];
    _gtBtn.showsTouchWhenHighlighted = YES;
    _gtBtn.layer.borderWidth = 0.8f;
    _gtBtn.layer.cornerRadius = 8.0f;
    _gtBtn.layer.borderColor = [UIColor clearColor].CGColor;
    [_gtBtn setTitle:@"云恢复" forState:UIControlStateNormal];
    _gtBtn.backgroundColor = CYColor(131, 195, 111, 1);
    [_gtBtn addTarget:self action:@selector(getcloud:) forControlEvents:UIControlEventTouchUpInside];
    
    _netpllb = [[UILabel alloc] initWithFrame:CGRectMake(self.view.width/10, self.view.height/5, 300, 30)];
    _netpllb.text = [NSString stringWithFormat:@"此次已备份人数: 0"];
    _netpllb.font = [UIFont systemFontOfSize:16.0];
    _netpllb.textColor = CYColor(131, 195, 111, 1);
    _cplb = [[UILabel alloc]initWithFrame:CGRectMake(_netpllb.x, self.netpllb.y+self.netpllb.hidden+30, self.netpllb.width+20, self.netpllb.height)];
    _cplb.textColor = CYColor(131, 195, 111, 1);
    _cplb.font = [UIFont systemFontOfSize:16.0];
    
    _copylb = [[UILabel alloc]init];
    _copylb.frame = CGRectMake(self.view.width/2.6,self.view.height/1.95, 150, 30);
    self.copylb.center = CGPointMake(self.view.center.x, self.copylb.center.y);
    _copylb.font = [UIFont systemFontOfSize:16.0];
    _copylb.backgroundColor = [UIColor clearColor];
    _copylb.textColor = [UIColor whiteColor];
    _copylb.textAlignment = NSTextAlignmentCenter;

    [self.view addSubview:_netpllb];
    [self.view addSubview:_gtBtn];
    [self.view addSubview:_cpBtn];
}

/**
 *  备份
 */
- (void)copycloud:(UIButton *)btn {
    @try {
        _tmlb.hidden         = YES;
        btn.enabled          = NO;
        CYUser *user         = [CYLoginHttpTool  userData].user;
        UIBezierPath *path   = [UIBezierPath bezierPath];
        CGRect rect          = [UIScreen mainScreen].applicationFrame;
        [path addArcWithCenter:CGPointMake(rect.size.width/2,rect.size.height/2+30) radius:self.view.width/4 startAngle:0 endAngle:2*M_PI clockwise:YES];
        arcLayer=[CAShapeLayer layer];
        arcLayer.path        = path.CGPath;//46,169,230
        arcLayer.fillColor   = CYColor(131, 195, 111, 1).CGColor;
        arcLayer.strokeColor = [UIColor whiteColor].CGColor;
        arcLayer.lineWidth   = 5;
        arcLayer.frame       = self.view.frame;
        _copylb.text         = @"备份中...";
        [self.view.layer addSublayer:arcLayer];
        [self.view addSubview:_copylb];
        [self drawLineAnimation:arcLayer];
        //获取时间节点
        [CYHttpTool postWithURL:[CYURL getNewVersionTime] params:@{@"userId":user.userId} success:^(id json) {
            CYJsonInfo *jsonInfo = [CYJsonInfo objectWithKeyValues:json]; NSDictionary *messageDic = jsonInfo.message;
            _versioncp = messageDic[@"time"];
            //        CYLog(@"versoncp = %@",_versioncp);
            _cplb.text = @"已更新至最新备份节点";
            [self.view addSubview:_cplb];
        } failure:^(NSError *error) {
            [MBProgressHUD showError:@"备份错误"];
        }];
        
        //获取云同步contacts参数
        NSArray *contactsArr = [CYMeTool contactsArr];
        
        for (NSDictionary *dic in contactsArr) {
            if (![dic[@"hashCode"] isEqualToString:@"0"] && dic[@"headerImage"]) {
                [CYHttpTool postCloudWithURL:[CYURL saveHeadImages] params:@{@"userId":user.userId,@"hashCode":dic[@"hashCode"]} image:dic[@"headerImage"] success:^(id json) {
                    CYLog(@"图片上传成功%@",json);
                    
                } failure:^(NSError *error) {
                    CYLog(@"失败:%@", error);
                } uploadProgress:^(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite) {
                    
                }];
            }
        }
        
        if (contactsArr.count && user) {
            //云同步
            [CYMeTool cloudSynWithSuccess:^(id json) {
                _copylb.text = @"备份成功";
                btn.enabled = YES;
                self.netpeople = json[@"message"][@"netSize"];
                self.netpllb.text = [NSString stringWithFormat:@"此次已备份人数: %@",self.netpeople];
            } failure:^(NSError *error) {
                CYLog(@"云同步: %@", error);
                _copylb.text = @"备份失败";
                btn.enabled = YES;
            } uploadProgress:^(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite) {
                
            }];
        } else {
            self.copylb.text = @"没有可备份的数据";
        }
    }
    @catch (NSException *exception) {
        _copylb.text = @"备份失败";
    }
}

#pragma mark - 恢复
/**
 *  恢复
 */
- (void)getcloud:(UIButton *)btn1 {
    @try {
        btn1.enabled = NO;
        CYUser *user = [CYLoginHttpTool  userData].user;
        //初始动画
        UIBezierPath *path = [UIBezierPath bezierPath];
        CGRect rect = [UIScreen mainScreen].applicationFrame;
        [path addArcWithCenter:CGPointMake(rect.size.width/2,rect.size.height/2+30) radius:self.view.width/4 startAngle:0 endAngle:2*M_PI clockwise:YES];
        arcLayer = [CAShapeLayer layer];
        arcLayer.path = path.CGPath;//46,169,230
        arcLayer.fillColor = CYColor(131, 195, 111, 1).CGColor;
        arcLayer.strokeColor = CYColor(255, 197, 0, 1).CGColor;
        arcLayer.lineWidth = 4.6;
        arcLayer.frame = self.view.frame;
        _copylb.text = @"恢复中...";
        [self.view.layer addSublayer:arcLayer];
        [self.view addSubview:_copylb];
        [self drawLineAnimation:arcLayer];
        //处理数据
        NSArray *contactsArr = [CYMeTool contactsArr];
        NSMutableArray *newContactsArr = [NSMutableArray array];
        if (contactsArr) {
            //去除字典中的headerImage
            for (NSDictionary *dic in contactsArr) {
                if (dic[@"headerImage"]) {
                    NSMutableDictionary *dicMu = [NSMutableDictionary dictionaryWithDictionary:dic];
                    [dicMu removeObjectForKey:@"headerImage"];
                    
                    [newContactsArr addObject:dicMu];
                } else {
                    [newContactsArr addObject:dic];
                }
            }
        } else {
            newContactsArr = [NSMutableArray arrayWithArray:contactsArr];
        }
        
        [CYHttpTool postWithURL:[CYURL getNewVersionTime] params:@{@"userId":user.userId} success:^(id json) {
            CYJsonInfo *jsonInfo = [CYJsonInfo objectWithKeyValues:json];
            if (jsonInfo.isSuccess) {
                NSDictionary *messageDic = jsonInfo.message;
                _versioncp = messageDic[@"time"];
                //            CYLog(@"version = %@",_versioncp);
                //若version == 0，表示之前没有备份过，提示请先备份
                if ([_versioncp isEqualToString:@"0"]) {
                    [MBProgressHUD hideHUDForView:self.view];
                    CYAlertView(@"您还没有备份过，请先备份");
                } else {
                    [CYHttpTool postWithURL:[CYURL getContactsByUserId] params:@{@"contacts":[NSString jsonStringWithArray:newContactsArr] ,@"userId":user.userId, @"version":_versioncp} success:^(id json) {
//                        CYLog(@"恢复数据成功%@",json);
                        btn1.enabled = YES;
                        _copylb.text = @"恢复成功";
                        
                        CYJsonInfo *jsonInfo = [CYJsonInfo objectWithKeyValues:json];
                        if (jsonInfo.isSuccess) {
                            [MBProgressHUD hideHUDForView:self.view];
                            NSDictionary *messageDic = jsonInfo.message;
                            
                            NSArray *deleteList = messageDic[@"deleteList"];//需删除的联系人
                            if (deleteList && deleteList.count) {
                                [self deletePersons:deleteList];
                            }
                            
                            NSArray *addList = messageDic[@"addList"];//新增加的联系人
                            if (addList && addList.count) {
                                [self deletePersons:addList];
                                [self addPersons:addList];
                            }
                        } else {
                            [MBProgressHUD hideHUDForView:self.view];
                            //恢复失败提示
                            CYAlertView(@"恢复失败，请稍候再试");
                            btn1.enabled = YES;
                        }
                        
                    } failure:^(NSError *error) {
                        [MBProgressHUD hideHUDForView:self.view];
                        CYLog(@"%@", error);
                    }];
                }
            } else {
                [MBProgressHUD hideHUDForView:self.view];
                //恢复失败提示
                CYAlertView(@"恢复失败，请稍候再试");
            }
        } failure:^(NSError *error) {
            [MBProgressHUD hideHUDForView:self.view];
            CYLog(@"%@", error);
        }];
    }
    @catch (NSException *exception) {
        _copylb.text = @"恢复失败";
    }
    
}

/**
 *  新增联系人
 *
 *  @param addList
 *
 *  @return
 */
- (BOOL)addPersons:(NSArray *)addList {
    NSMutableArray *addListModel = [NSMutableArray array];
    [addList enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        CYCloudPerson *person = [CYCloudPerson objectWithKeyValues:obj];
        [addListModel addObject:person];
    }];
    //添加数据到通讯录
    [CYMeTool addABPersons:addListModel success:^(NSArray *arr) {
//        CYAlertView(CYStringFormat(@"云同步新增：%lu条数据", (unsigned long)arr.count));
        self.netpllb.text = [NSString stringWithFormat:@"此次已恢复人数: %lu",((unsigned long)arr.count)];
        _tmlb.text = [NSString stringWithFormat:@"当前恢复节点:%@",_versiongt];
        
    } failure:^(NSArray *arr) {
//        CYAlertView(CYStringFormat(@"云同步新增失败：%lu条数据", (unsigned long)arr.count));
    }];
    return YES;
}

/**
 *  删除联系人
 *
 *  @param deleteList
 *
 *  @return
 */
- (BOOL)deletePersons:(NSArray *)deleteList {
    NSMutableArray *deleteListModel = [NSMutableArray array];
    [deleteList enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        CYCloudPerson *person = [CYCloudPerson objectWithKeyValues:obj];
        [deleteListModel addObject:person];
    }];
    //删除通讯录数据
    [CYMeTool deleteABPerson:deleteListModel success:^(NSArray *arr) {
//        CYAlertView(CYStringFormat(@"云同步删除：%lu条数据", (unsigned long)arr.count));
        //删除收藏中的存在的记录
        BOOL result = [[CYDatabase sharedDatabase] deleteCollectionsWithPersons:arr];
        CYLog(@"收藏删除是否成功: %d", result);
        
    } failure:^(NSArray *arr) {
//        CYAlertView(CYStringFormat(@"云同步删除失败：%lu条数据", (unsigned long)arr.count));
    }];
    return YES;
}

-(void)drawLineAnimation:(CALayer*)layer {
    //动画控制器
    CABasicAnimation *bas=[CABasicAnimation animationWithKeyPath:@"strokeEnd"];
    bas.duration=2;
    bas.delegate=self;
    bas.fromValue=[NSNumber numberWithInteger:0];
    bas.toValue=[NSNumber numberWithInteger:1];
    [layer addAnimation:bas forKey:@"key"];
}
@end


//时光机，备用
//获取网络联系人
//        [CYHttpTool postWithURL:[CYURL getCurrentContacts]params:@{@"userId":user.userId} success:^(id json) {
//            CYLog(@"获取网络联系人成功%@",json);
//            self.netpeople = json[@"message"][@"currentNumber"];
//            NSLog(@"peoplenumber = %@",self.netpeople);
//            _netpllb.text = [NSString stringWithFormat:@"已储存网络人数:%@",self.netpeople];
//            CYJsonInfo *jsonInfo = [CYJsonInfo objectWithKeyValues:json];
//            if (jsonInfo.isSuccess) {
//
//
//            } else {
//
//            }
//        }
//                failure:^(NSError *error) {
//                CYLog(@"失败:%@",error);
//        }];
//


